﻿namespace My.Hydrator.Conventions
{
    using System;
    using System.ComponentModel.Composition;
    using My.Hydrator.Helpers;

    [Export(typeof(ITypeConvention))]
    public class StringTypeConvention : BaseTypeConvention, ITypeConvention
    {
        private readonly int stringLength;

        public StringTypeConvention() : this(100)
        {
        }

        public StringTypeConvention(int stringLength)
        {
            this.stringLength = stringLength;
        }

        public Type Type
        {
            get { return typeof(string); }
        }

        public object GenerateValue(object[] customAttributes)
        {
            this.GetAttributes(customAttributes);

            string result = null;

            if (this.IsDataTypeAttributePresent)
            {
                var formatter = this.GetFormatter(DataTypeAttribute);
                if (formatter != null)
                {
                    result = formatter.GetFormat() as string;
                }
            }
            else
            {
                result = string.Empty;

                for (var i = 0; i < this.stringLength; i++)
                {
                    result += this.Random.NextUpperCaseLetter();
                }
            }

            if (!string.IsNullOrEmpty(result))
            {
                if (this.IsStringLengthAttributePresent)
                {
                    result.Substring(0, Math.Min(result.Length, StringLengthAttribute.MaximumLength));
                }
            }

            return result;
        }
    }
}
